package com.xxx.auth.entity;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.xxx.auth.entity.enums.Status;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.Accessors;
import org.hibernate.annotations.Comment;
import org.hibernate.annotations.GenericGenerator;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
@Entity
@Comment("应用表")
@Table(name = "t_application")
@EntityListeners(AuditingEntityListener.class)
public class Application extends TimeEntity implements Serializable {

    public static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(generator = "CustomUUID")
    @GenericGenerator(name = "CustomUUID", strategy = "com.xxx.auth.common.generator.CustomUUIDGenerator")
    @Column(name = "id", unique = true)
    private String id;

    @Schema(title = "名称")
    @Column
    private String name;

    @Schema(title = "描述")
    @Column
    private String description;

    @Schema(title = "APP Secret")
    @Column
    private String appSecret;

    @Column
    @Comment("创建者")
    @Schema(title = "创建者")
    private String creatorId;

    @Column
    @Comment("状态：NORMAL-正常 RECYCLED-回收站 DELETED-删除")
    @Schema(title = "状态：NORMAL-正常 RECYCLED-回收站 DELETED-删除")
    @Enumerated(EnumType.STRING)
    private Status status = Status.NORMAL;

    @ManyToMany(targetEntity = User.class, fetch = FetchType.LAZY)
    @JoinTable(name = "t_application_user", joinColumns = @JoinColumn(name = "application_id", referencedColumnName = "id", foreignKey = @ForeignKey(name = "none", value = ConstraintMode.NO_CONSTRAINT)), inverseJoinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id", foreignKey = @ForeignKey(name = "none", value = ConstraintMode.NO_CONSTRAINT)))
    @JsonIgnore
    private Set<User> userSet = new HashSet<>();

    @ManyToMany(targetEntity = Permission.class, fetch = FetchType.EAGER)
    @JoinTable(name = "t_application_permission", joinColumns = @JoinColumn(name = "application_id", referencedColumnName = "id", foreignKey = @ForeignKey(name = "none", value = ConstraintMode.NO_CONSTRAINT)), inverseJoinColumns = @JoinColumn(name = "permission_id", referencedColumnName = "id", foreignKey = @ForeignKey(name = "none", value = ConstraintMode.NO_CONSTRAINT)))
    @JsonIgnore
    private Set<Permission> permissionSet = new HashSet<>();

    public Application(String name, String creatorId) {
        this.name = name;
        this.creatorId = creatorId;
    }
}
